﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RemoteTool.Common;
using RemoteTool.Server.Models;
using RemoteTool.Server.ViewModels;
using RemoteToolData.Data;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using X.PagedList;

namespace RemoteTool.Server.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        public static readonly int PageSize = 10;
        private readonly ILogger<HomeController> logger;
        private readonly IConfiguration configuration;
        private readonly ApplicationDbContext dbContext;
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly UserManager<ApplicationUser> userManager;

        public HomeController(ILogger<HomeController> logger, IConfiguration configuration,
            ApplicationDbContext dbContext, IWebHostEnvironment webHostEnvironment,
            UserManager<ApplicationUser> userManager)
        {
            this.logger = logger;
            this.configuration = configuration;
            this.dbContext = dbContext;
            this.webHostEnvironment = webHostEnvironment;
            this.userManager = userManager;
        }

        public async Task<IActionResult> Index(int page = 1)
        {
            try
            {
                var list = await dbContext.DeviceInfos.ToListAsync();
                if (list?.Count > 0)
                {
                    SortedDictionary<string, DeviceInfo> dictionary = new SortedDictionary<string, DeviceInfo>();
                    foreach (var item in list)
                    {
                        if (dictionary.ContainsKey(item.ProjectName) == false)
                            dictionary.Add(item.ProjectName, item);
                    }

                    ViewBag.OperaMsg = $"总共查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    var infos = list.ToPagedList<DeviceInfo>(page, PageSize);
                    return View(infos);
                }
                else
                {
                    ViewBag.OperaMsg = $"当前没有设备信息记录！";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询设备信息发生异常->{ex.Message}");
            }
            return View();
        }

        public IActionResult Login()
        {
            return View();
        }

        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> AddDeviceInfo(DeviceInfoViewModel info)
        {
            try
            {
                var deviceInfo = new DeviceInfo();
                deviceInfo.CopyObjValue(info);
                deviceInfo.GuidCode = Guid.NewGuid().ToString("N");
                deviceInfo.CreatorName = User.Claims.First(p => p.Type == "UserName").Value;
                // 查找设备
                var infos = await dbContext.DeviceInfos.ToListAsync();
                var device = infos.Find(p => p.Equals(deviceInfo));
                if (device == null)
                {
                    dbContext.DeviceInfos.Add(deviceInfo);
                    dbContext.SaveChanges();

                    var list = await dbContext.DeviceInfos.ToListAsync();
                    var infos2 = list.ToPagedList<DeviceInfo>(1, PageSize);
                    return View("Index", infos2);
                }
                else
                {
                    ViewBag.ErrorMsg = $"已经存在该远程设备";
                    return View("~/Views/Error/Error.cshtml");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"添加设备信息发生异常->{ex.Message}");
            }
            return View("Index");
        }

        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> DeleteDeviceInfo(int id)
        {
            try
            {
                // 查找设备
                var device = await dbContext.DeviceInfos.FindAsync(id);
                if (device == null)
                {
                    ViewBag.ErrorMsg = $"找不到id={id}的设备";
                    return View("~/Views/Error/Error.cshtml");
                }
                else
                {
                    dbContext.DeviceInfos.Remove(device);
                    dbContext.SaveChanges();
                    //res.message = $"id={id}的设备删除成功";
                    //res.success = true;
                    return View("Index");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"删除id={id}的设备信息发生异常->{ex.Message}");
            }
            return View("Index");
        }
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpGet]
        public async Task<IActionResult> DeleteDeviceInfo(string guidCode)
        {
            try
            {
                // 查找设备
                var device = await dbContext.DeviceInfos.Where(p => p.GuidCode == guidCode).FirstOrDefaultAsync();
                if (device == null)
                {
                    ViewBag.ErrorMsg = $"找不到guidCode={guidCode}的设备";
                    return View("~/Views/Error/Error.cshtml");
                }
                else
                {
                    if (device.CreatorName == User.Claims.First(p => p.Type == "UserName").Value)
                    {
                        dbContext.DeviceInfos.Remove(device);
                        dbContext.SaveChanges();
                        //res.message = $"guidCode={guidCode}的设备删除成功";
                        //res.success = true;
                        return View("Index");
                    }
                    else
                    {
                        ViewBag.ErrorMsg = $"当前设备创建者为：{device.CreatorName},你无权删除！";
                        return View("~/Views/Error/Error.cshtml");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"删除guidCode={guidCode}的设备信息发生异常->{ex.Message}");
            }

            return View("Index");
        }
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> ModifyDeviceInfo(DeviceInfoViewModel info)
        {
            try
            {
                // 查找设备
                var device = await dbContext.DeviceInfos.Where(_ => _.GuidCode == info.GuidCode).FirstOrDefaultAsync();
                if (device == null)
                {
                    ViewBag.ErrorMsg = $"找不到guidCode={info.GuidCode}的设备";
                    return View("~/Views/Error/Error.cshtml");
                }
                else
                {
                    device.CopyObjValue(info);
                    dbContext.SaveChanges();
                    //res.message = $"guidCode={info.GuidCode}的设备更新成功";
                    //res.success = true;
                    return View("Index");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"修改guidCode={info.GuidCode}的设备信息发生异常->{ex.Message}");
            }
            return View("Index");
        }

        [HttpGet]
        public async Task<IActionResult> Search(string keyword)
        {
            //var model = new HomeViewModel();
            List<DeviceInfo> list = new List<DeviceInfo>();
            try
            {
                var regexStr1 = @"^[0-9]+$";
                var regexStr2 = @"^[0-9a-zA-z]+$";
                if (string.IsNullOrEmpty(keyword))
                {
                    list = await dbContext.DeviceInfos
                              .OrderByDescending(p => p.LastTime).ToListAsync();
                }
                else if (Regex.IsMatch(keyword.Trim(), regexStr1))
                {
                    list = await dbContext.DeviceInfos
                                .Where(p => p.OraySunId.Replace(" ", "").Contains(keyword.Replace(" ", "")) ||
                                            p.ToDeskId.Replace(" ", "").Contains(keyword.Replace(" ", "")))
                                .OrderByDescending(p => p.LastTime).ToListAsync();
                }
                else if (Regex.IsMatch(keyword.Trim(), regexStr2))
                {
                    list = await dbContext.DeviceInfos
                                .Where(p => p.DeviceSerialNo.Contains(keyword.Trim()))
                                .OrderByDescending(p => p.LastTime).ToListAsync();
                }
                else
                {
                    var keys = keyword?.Split(new string[] { " ", ":", "：", "|" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (keys?.Count() > 1)
                    {
                        list = await dbContext.DeviceInfos
                                 .Where(p => p.ProjectName.Contains(keys[0]) || p.DeviceName.Contains(keys[1]))
                                 .OrderByDescending(p => p.LastTime).ToListAsync();
                    }
                    else if (keys?.Count() == 1)
                    {
                        list = await dbContext.DeviceInfos
                            .Where(p => p.ProjectName.Contains(keys[0]) || p.DeviceName.Contains(keys[0]))
                            .OrderByDescending(p => p.LastTime).ToListAsync();

                    }
                    else
                    {
                        list = await dbContext.DeviceInfos.OrderByDescending(p => p.LastTime).ToListAsync();
                    }
                }

                if (list?.Count() > 0)
                {
                    SortedDictionary<string, DeviceInfo> dictionary = new SortedDictionary<string, DeviceInfo>();
                    foreach (var item in list)
                    {
                        if (dictionary.ContainsKey(item.ProjectName) == false)
                            dictionary.Add(item.ProjectName, item);
                    }
                   
                    ViewBag.OperaMsg = $"当前页查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    var infos = list.ToPagedList<DeviceInfo>(1, PageSize);
                    return View("Index", infos);
                }
                else
                {
                    ViewBag.OperaMsg = $"找不到关键字为{keyword}的设备";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询关键词为->{keyword}的设备信息发生异常->{ex.Message}");
            }
            return View("Index");
        }

        [AllowAnonymous]
        [HttpPost]
        public IActionResult Modify(EditProfileViewModel model)
        {
            var pmodel = new ProfileViewModel();
            if (ModelState.IsValid)
            {
                var user = dbContext.Users.Where(p => p.UserName == model.UserName).FirstOrDefault();
                if (user != null)
                {
                    user.Email = model.Email;
                    if (model.Photo != null)
                    {
                        var uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, @"img/user");
                        var uniqueFileName = Guid.NewGuid().ToString() + model.Photo.FileName;
                        var filePath = Path.Combine(uploadFolder, uniqueFileName);
                        model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                        //foreach (var item in model.Photos)
                        //{
                        //    var uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");
                        //    uniqueFileName = Guid.NewGuid().ToString() + item.FileName;
                        //    var filePath = Path.Combine(uploadFolder, uniqueFileName);
                        //    item.CopyTo(new FileStream(filePath, FileMode.Create));
                        //}
                        user.Portrait = uniqueFileName;
                    }
                    dbContext.SaveChanges();
                    pmodel.UserName = user.UserName;
                    pmodel.Email = user.Email;
                    pmodel.Photo = user.Portrait;
                }
            }
            return View("~/Views/Profile/MyProfile.cshtml", pmodel);

        }


        public IActionResult Privacy()
        {
            return View();
        }

        public IActionResult Unsupported()
        {
            return View();
        }

        public IActionResult Buttons()
        {
            return View("~/Views/Home/Components/Buttons.cshtml");
        }

        public IActionResult Cards()
        {
            return View("~/Views/Home/Components/Cards.cshtml");
        }

        public IActionResult Bleach()
        {
            return View("~/Views/Home/Pages/Cartoon/Bleach.cshtml");
        }

        public IActionResult Naruto()
        {
            return View("~/Views/Home/Pages/Cartoon/Naruto.cshtml");
        }
        public IActionResult OnePiece()
        {
            return View("~/Views/Home/Pages/Cartoon/OnePiece.cshtml");
        }
        public IActionResult SpiritCage()
        {
            return View("~/Views/Home/Pages/Cartoon/SpiritCage.cshtml");
        }
        public IActionResult Scenery()
        {
            return View("~/Views/Home/Pages/Scenery/Scenery.cshtml");
        }

        public IActionResult Colors()
        {
            return View("~/Views/Home/Utilities/Colors.cshtml");
        }
        public IActionResult Borders()
        {
            return View("~/Views/Home/Utilities/Borders.cshtml");
        }
        public IActionResult Animations()
        {
            return View("~/Views/Home/Utilities/Animations.cshtml");
        }
        public IActionResult Others()
        {
            return View("~/Views/Home/Utilities/Others.cshtml");
        }

        public IActionResult Charts()
        {
            return View("~/Views/Home/Charts.cshtml");
        }
        public IActionResult Tables()
        {
            return View("~/Views/Home/Tables.cshtml");
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult ActivityLog()
        {
            return View();
        }

    }
}